/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.jboss.weld.bootstrap.api.Environment;

/**
 * this class saves all logs in a file
 * @author gabriellebotbol
 */
public class FileHandler extends Handler
{

    private File file=new File("log.log");
    private FileOutputStream stream = null;

    public FileHandler() 
    {
        if(!this.file.exists())
        {
            try 
            {
                this.file.createNewFile();
            } 
            catch (IOException ex) 
            {
                Logger.global.log(Level.SEVERE, null, ex);
            }
        }
        if(this.file.canWrite())
        {
            try 
            {
                stream=new FileOutputStream(file);
            } 
            catch (FileNotFoundException ex) 
            {
                Logger.global.log(Level.SEVERE, null, ex);
            }
        }
    }
    
    
    
    @Override
    public void publish(LogRecord record) 
    {
        String content="Level : "+record.getLevel() + " Date : "+new Date(record.getMillis())+" Message : "+record.getMessage()+"\n";
        if(stream!=null)
        {
            try 
            {
                stream.write(content.getBytes());
            } 
            catch (IOException ex) 
            {
                Logger.global.log(Level.SEVERE, null, ex);
            }
        }
        else
        {
            System.out.println(content);
        }
    }

    @Override
    public void flush() 
    {
        
    }

    @Override
    public void close() throws SecurityException 
    {
        if(stream!=null)
        {
            try 
            {
                stream.close();
            } 
            catch (IOException ex) 
            {
                Logger.global.log(Level.SEVERE, null, ex);
            }
        }
    }

}
